import React, { Component } from "react";
// Prompt组件就是用于防止路由跳转的
import { Link, Route, Switch, Prompt } from "react-router-dom";

class Home extends Component {
  state = {
    textValue: "",
  };
  handleChange = (e) => {
    this.setState({
      textValue: e.target.value,
    });
  };
  render() {
    return (
      <>
        <div>这是home组件</div>
        <input
          type="text"
          value={this.state.textValue}
          onChange={this.handleChange}
        />

        {/* 里面有两个属性, when表示条件, message表示的是提示信息 */}
        <Prompt
          when={this.state.textValue}
          message={(location) =>
            `Are you sure you want to go to ${location.pathname}`
          }
        />
      </>
    );
  }
}

class About extends Component {
  render() {
    return <div>这是About组件</div>;
  }
}

class Mine extends Component {
  render() {
    return <div>这是Mine组件</div>;
  }
}

class App extends Component {
  render() {
    return (
      <>
        <h2>react-router-阻止跳转</h2>
        <ul>
          <li>
            <Link to="/home">首页</Link>
          </li>
          <li>
            <Link to="/about">关于页</Link>
          </li>
          <li>
            <Link to="/mine">我的页</Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Route path="/home" component={Home} exact></Route>
          <Route path="/about" component={About}></Route>
          <Route path="/mine" component={Mine}></Route>
        </Switch>
      </>
    );
  }
}

export default App;
